# Create your views here.
from django.http import HttpResponse, HttpResponseBadRequest

from common.sql_constant_enum import Bug_status_constant_responding_English
from common.sql_instance_project import *
from utils.cursorHandler import *
from utils.normal_simple_function import serialize_json_dumps, compute_rank_6_efficient, serialize_json_date_type, \
    get_file_dirname_path, read_pkl_file
import datetime
from pprint import pprint
import asyncio

async def historyBugPriority(request):
    """
        本函数用于处理 “历史未解决Bug严重等级情况”
    :param request:
    :return:
    """
    if request.method == 'GET':
        all_priority_degrees = cursor.search_alone(history_bug_priority_discribute)
        pprint(all_priority_degrees)
        # 优先等级构造
        priority_degree_level: dict = {1: 'p0', 2: 'p1', 3: 'p2', 4: 'p3'}
        all_count = 0
        # 优先级分布字典初始化
        priority_degree_distribute = {}
        for item in all_priority_degrees:
            all_count += int(item['count'])
            priority_degree_distribute[priority_degree_level[int(item['severity'])]] = int(item['count'])
        json_returns = {
            'data': {
                "history_unsolved_bug_priority_distribution_situation": {
                    each_priority: round(each_count / all_count * 100, 0) for each_priority, each_count in priority_degree_distribute.items()
                }
            }
        }
        response = HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
        return response
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')


async def rankBoard(request):
    """
        本函数用于处理 “排行榜”
    :param request:
    :return:
    """
    if request.method == 'GET':
        # 获取get请求带的参数
        date_range = int(request.GET.get('date_range', 7))
        # 榜单人员查询结果
        name_nums: list(dict) = cursor.search_alone(Bug_efficient_rank_6)
        # 计算有效率排行人员名单
        rank_6_efficient:list = compute_rank_6_efficient(name_nums)[:6]
        print('rank_6--------------',rank_6_efficient)

        json_returns = {
            'data': {
                # 排行榜
                "rank_board": {
                    # Bug创建排行榜
                    "Bug_create_rank": {
                        "today": [
                            {item['name']: item['count'] } for item in cursor.search_alone(Bug_creator_rank_6)
                        ]
                    },
                    # Bug有效率排行榜
                    "Bug_efficient_rank": {
                        "today": [
                            {person_compare[0]: person_compare[1][1]} for person_compare in rank_6_efficient
                        ]
                    },
                    # Bug未解决排行榜
                    "Bug_unsolved_rank": {
                        "today": [
                            {item['name']: item['count']} for item in cursor.search_alone(Bug_unsolved_rank_6)
                        ]
                    }
                }
            }
        }
        response = HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
        return response
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')


async def BugData(request):
    """
        本函数用于处理： 迭代版本中 版本状态分布直方图 & 曲线图
    :param request:
    :return:
    """

    if request.method == 'GET':
        # 获取get请求带的参数
        date_range = int(request.GET.get('date_range', 7))
        # 定位项目集
        position_project_ids_names = cursor.search_alone(postion_project_id_names_sql)
        position_unsolved_num = cursor.search_alone(construct_sql_position_bug_unsolved_statistics(
            project_ids=tuple( each_project['id'] for each_project in position_project_ids_names)))[0].get('count', -1)
        # 地图项目集
        map_project_ids_names = cursor.search_alone(map_project_id_names_sql)
        # map_unsolved_num = cursor.search_alone(construct_sql_map_bug_unsolved_statistics(
        #     project_ids=tuple( each_project['id'] for each_project in map_project_ids_names)))[0].get('count', -1)
        # 调试代码，上述代码在正式禅道中正常获取数据
        map_unsolved_num = 50
        # 交付项目集
        deliver_project_ids_names = cursor.search_alone(deliver_project_id_names_sql)
        deliver_unsolved_num = cursor.search_alone(construct_sql_deliver_bug_unsolved_statistics(
            project_ids=tuple( each_project['id'] for each_project in deliver_project_ids_names)))[0].get('count', -1)
        json_returns = {
            'data': {
                "Bug_data": {
                    # 当月未解决Bug分布饼图
                    "this_mouth_unsolved_bug_distribute_pie": {
                        "postion": position_unsolved_num,
                        "map": map_unsolved_num,
                        "deliver": deliver_unsolved_num
                    },
                    # 当月Bug 直方图
                    "this_mouth_bug_histogram": {
                        "bug_add_histogram": [
                            {'date': str(datetime.date.today() + datetime.timedelta(-i)),
                             'num': cursor.search_alone(construct_bug_each_day_add_histogram_sql(i))[0].get(
                                                  'count', 0) if cursor.search_alone(construct_bug_each_day_closed_line_sql(i))[0].get(
                                                  'count', 0) > 0 else 0} \
                            for i in range(date_range, 0, -1)
                        ],
                        "date_range": date_range
                    },
                    # 当月 Bug 曲线图
                    "this_mouth_bug_line": {
                        "bug_close_line": [
                            {'date': str(datetime.date.today() + datetime.timedelta(-i)), 'num':
                                              cursor.search_alone(construct_bug_each_day_closed_line_sql(i))[0].get(
                                                  'count', 0)} \
                                         for i in range(date_range, 0, -1)
                        ],
                        "date_range": date_range
                    }
                }
            }
        }
        response = HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
        return response
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')


async def historyBugDelay(request):
    """
        本函数用于处理 历史未解决Bug超时情况
    :param request:
    :return:
    """
    if request.method == 'GET':

        json_returns = {
            'data': {
                # 历史未解决Bug超时情况
                # 简化 {each_days: cursor.search_alone(construct_bug_sql_history_Bug_delay(delay_days_start=int(each_days.split('-')[0]), delay_days_end=))[0]each_days.split('-')[0][:-4]).get('count', -1) for each_days in ["30-60days", "15-30days", "7-15days", "2-7days"]}
                "history_unsolved_bug_delay_situation": {
                    "60-365days": cursor.search_alone(construct_bug_sql_history_Bug_delay(delay_days_start=60, delay_days_end=365))[0].get('count', -1),
                    "30-60days": cursor.search_alone(construct_bug_sql_history_Bug_delay(delay_days_start=30, delay_days_end=60))[0].get('count', -1),
                    "15-30days": cursor.search_alone(construct_bug_sql_history_Bug_delay(delay_days_start=15, delay_days_end=30))[0].get('count', -1),
                    "7-15days": cursor.search_alone(construct_bug_sql_history_Bug_delay(delay_days_start=7, delay_days_end=15))[0].get('count', -1),
                    "2-7days": cursor.search_alone(construct_bug_sql_history_Bug_delay(delay_days_start=2, delay_days_end=7))[0].get('count', -1),
                    "0-2days": cursor.search_alone(construct_bug_sql_history_Bug_delay(delay_days_start=0, delay_days_end=2))[0].get('count', -1)
                }
            }
        }
        response = HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
        return response
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')



async def dataOverview(request):
    """
        本函数处理“进行中版本数”， “已上线版本数“， ”未解决Bug总数“ & 曲线图

    :param request: date_range 曲线图的周期
    :return:
    """
    if request.method == 'GET':
        # 获取get请求带的参数
        date_range = int(request.GET.get('date_range', 7))
        # 版本中各个状态的统计
        verion_status_nums = cursor.search_alone(version_status_sql)
        # 未处理bug总数统计
        unsolved_bug_nums = cursor.search_alone(unsolved_bug_sql)
        print(unsolved_bug_sql)
        # 正在运行中的 “测试单” 前一天的数据了统计
        lastday_increase_open_tasttask_1_day_num = cursor.search_alone(construct_n_day_sql_lastday_increase_open_testtask(nday=1))[0].get('count')
        # 正在运行中的 “测试单” 前2天的数据了统计
        # lastday_increase_open_tasttask_2_day_num = cursor.search_alone(construct_n_day_sql_lastday_increase_open_testtask(nday=2))[0].get('count')
        # 已上线的 “测试单” 前一天的数据统计
        lastday_increase_done_tasttask_1_day_num = cursor.search_alone(construct_n_day_sql_lastday_increase_done_tasttask(nday=1))[0].get('count')
        # 已上线的 “测试单” 前2天的数据统计
        # lastday_increase_done_tasttask_2_day_num = cursor.search_alone(construct_n_day_sql_lastday_increase_done_tasttask(nday=2))[0].get('count')
        # 未解决 “bug”  前一天的数据统计
        lastday_increase_bug_1_day_num = cursor.search_alone(construct_n_day_sql_lastday_increase_unsolved_bug(nday=1))[0].get('count')
        # 未解决 “bug”  前2天的数据统计
        # lastday_increase_bug_2_day_num = cursor.search_alone(construct_n_day_sql_lastday_increase_unsolved_bug(nday=2))[0].get('count')

        # 分别获取各个状态 “测试单”的数据
        for each_status in verion_status_nums:
            if each_status.get('status', None) == 'closed':
                has_done_veresion = each_status['count']
            if each_status.get('status', None) == 'doing':
                doing_version = each_status['count']
        # 分别获取各个状态 “Bug”的数据
        for each_bug_status in unsolved_bug_nums:
            if each_bug_status.get('status') == 'active':
                bug_active = each_bug_status['count']
            if each_bug_status.get('status') == 'closed':
                bug_closed = each_bug_status['count']
            if each_bug_status.get('status') == 'resolved':
                bug_resolved = each_bug_status['count']
        # else:
        #     bug_active = bug_resolved + bug_active

        # 从当前未解决Bug状态统计，昨日，前日.....的处理方案
        bug_file = get_file_dirname_path(__file__, par_dir=True, concat_file=unsovleDailyBug_file)
        file_data_record = read_pkl_file(bug_file)
        data_dot = []

        for i in range(date_range - 1, -1, -1):
            # 被统计的日期
            statistic_day = str(datetime.date.today() + datetime.timedelta(-i))
            # 参照日期
            compare_day = str(datetime.date.today() + datetime.timedelta(-i + 1))
            print('统计日期为：=》', statistic_day)
            # 1. 今日未解决Bug
            today_unsolved_num = cursor.search_alone(today_unsolved_bug_sql)[0].get('count')
            # 当日的话，不用做加减法
            if i == 0:
                data_dot.append({
                    statistic_day: today_unsolved_num if today_unsolved_num > 0 else 0
                })
                continue
            # 使用历史的数据
            elif statistic_day in file_data_record:
                print(f'<-^-> 当前使用了历史存储的文件数据 {statistic_day} {file_data_record[statistic_day]}')
                data_dot.append({
                    statistic_day: file_data_record[statistic_day]
                })
                continue
            # 历史数据都没有，则计算
            # 2. 新提交的Bug
            new_commit_num = cursor.search_alone(construct_bug_new_commit_by_date_range(_start_date=compare_day))[0].get('count')
            # 3. 已解决统计日之前的Bug
            solved_history_num = cursor.search_alone(construct_bug_solved_history_by_date_range(
                _create_start_date=compare_day,
                _sovled_end_date=compare_day
            ))[0].get('count')
            data_dot.append(
                    {statistic_day: today_unsolved_num - new_commit_num + solved_history_num if today_unsolved_num - new_commit_num + solved_history_num > 0 else 0}
                )

        # 返回的数据结构，组件数据结果
        json_returns = {
            'data': {
                # 数据概览板块
                'data_overview': {
                    # 正在进行中的迭代版本
                    "running_version": {
                        'total_num': doing_version,
                        'yesterday_add': lastday_increase_open_tasttask_1_day_num,
                        # 'day_compare_increase': f'''{float(lastday_increase_open_tasttask_1_day_num / lastday_increase_open_tasttask_2_day_num * 100)}%''' if lastday_increase_open_tasttask_2_day_num else '0.0%'
                    },
                    # 已关闭的版本
                    'onlined_version': {
                        'total_num': has_done_veresion,
                        'yesterday_add': lastday_increase_done_tasttask_1_day_num,
                        # 'day_compare_increase': f'''{float(lastday_increase_done_tasttask_1_day_num / lastday_increase_done_tasttask_2_day_num * 100)}%''' if lastday_increase_done_tasttask_2_day_num else '0.0%'
                    },
                    # 未解决Bug数
                    'unsolved_bug': {
                        'total_num': bug_active,
                        'yesterday_add': lastday_increase_bug_1_day_num,
                        # 'day_compare_increase': f'''{float(lastday_increase_bug_1_day_num / lastday_increase_bug_2_day_num * 100)}%''' if lastday_increase_bug_2_day_num else '0.0%'
                    },
                    # 数据概览-未解决Bug曲线图
                    "unsolved_bug_plot": {
                        "data_dot": data_dot,
                        "date_range": date_range
                    }
                }
            }
        }
        response = HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
        return response
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')


async def IterationVersion(request):
    """
        本函数用于处理： 迭代版本中的饼图
    :param request: date_range： 日期范围由前端提供
    :return:
    """
    if request.method == 'GET':
        # 获取get请求带的参数
        date_range = int(request.GET.get('date_range', 7))

        json_returns = {
            'data': {
                "version_status_destribute_pie": {
                    "normal_closed": cursor.search_alone(construct_testtask_sql_normal_closed_testtask(_date_range=date_range))[0].get('count', -1),
                    "delay_closed": cursor.search_alone(construct_testtask_sql_delay_closed_testtask(_date_range=date_range))[0].get('count', -1)
                }
            }
        }
        response = HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
        return response
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')


async def iterationVersionExtension(request):
    """
        本函数用于处理： 迭代版本中 版本状态分布直方图 & 曲线图
    :param request:
    :return:
    """

    if request.method == 'GET':
        # 获取get请求带的参数
        date_range = int(request.GET.get('date_range', 7))
        project_iteration_num = cursor.search_alone(project_statistic_iteration_status_num_sql)
        print(project_iteration_num)
        # 初始化返回值
        json_returns ={'data': {"Iteration_version": {"version_status_destribute_histogram": {"runing_version": []}}}, "date_range": date_range}
        returns_value_list = []
        for each_project in project_iteration_num:
            returns_value_list.append(
                {'name': each_project['name'],
                 'runing_version_num': each_project['doing'],
                 'blocking_version_num': each_project['suspended'] + each_project['wait'],
                 'closed_version': each_project['closed']}
            )
        # 处理按照正在进行中排序
        returns_value_list = sorted(returns_value_list, key=lambda item: item['runing_version_num'], reverse=True)
        json_returns['data']['Iteration_version']["version_status_destribute_histogram"]["runing_version"] = returns_value_list
        # print(f'returns_value_list = {returns_value_list}')
        response = HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
        return response
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')



async def iterationVersionExtension_old(request):
    """
        本函数用于处理： 迭代版本中 版本状态分布直方图 & 曲线图
    :param request:
    :return:
    """

    if request.method == 'GET':
        # 获取get请求带的参数
        date_range = int(request.GET.get('date_range', 7))
        # 定位项目集
        position_project_ids_names = cursor.search_alone(postion_project_id_names_sql)
        # 查询到 定位 项目集测试单各个状态的统计结果
        position_project_tasktest_status = cursor.search_alone(construct_sql_project_collection_testtask_staus_statistics(
            project_ids=tuple( each_project['id'] for each_project in position_project_ids_names), date_range=date_range))
        # 地图项目集
        map_project_ids_names = cursor.search_alone(map_project_id_names_sql)
        # 查询到 地图 项目集测试单各个状态的统计结果
        map_project_tasktest_status = cursor.search_alone(construct_sql_project_collection_testtask_staus_statistics(
            project_ids=tuple( each_project['id'] for each_project in map_project_ids_names), date_range=date_range))

        # 交付项目集
        deliver_project_ids_names = cursor.search_alone(deliver_project_id_names_sql)
        # 查询到 地图 项目集测试单各个状态的统计结果
        deliver_project_tasktest_status = cursor.search_alone(construct_sql_project_collection_testtask_staus_statistics(
            project_ids=tuple( each_project['id'] for each_project in deliver_project_ids_names), date_range=date_range))

        json_returns = {
            'data': {
                "Iteration_version": {
                    "version_status_destribute_histogram": {
                        "runing_version": [
                            {'name': each_project['name'], 'runing_version_num': each_project['doing'], 'blocking_version_num': each_project['blocked'], 'closed_version': each_project['closed']} for each_project in
                            position_project_tasktest_status + map_project_tasktest_status + deliver_project_tasktest_status
                        ]
                    }
                },
                "date_range": date_range
            }
        }
        response = HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
        return response
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')




async def BugDetailList(request):
    """
        此接口要返回Bug清单，包含大于30天，严重等级为严重级别以上的Bug详情
    :param request:
    :return:
    """
    if request.method == 'GET':
        print(Bug_detail_list_of_delay_30_and_severity_1_sql)
        Bug_condition_search_result = cursor.search_alone(Bug_detail_list_of_delay_30_and_severity_1_sql)
        json_returns = {
            'data': {
                "Bug_total": len(Bug_condition_search_result),  # Bug总数
                "Bug_detail_list": [{
                    # 项目名
                    "project_name": each_bug.get('project_name'),
                    # 子系统
                    "subsys_name": each_bug.get('subsys_name'),
                    # BugId
                    "Bug_id": each_bug.get('bug_id'),
                    # Bug严重程度
                    "Bug_priority": each_bug.get('severity'),
                    # Bug标题
                    "Bug_title": each_bug.get('title'),
                    # 创建人
                    "creator": each_bug.get('creator'),
                    # 创建时间
                    "create_date": serialize_json_date_type(each_bug.get('create_date')),
                    # 创建人
                    "assigner": each_bug.get('assigner'),
                    # 创建时间
                    "sovled_date": serialize_json_date_type(each_bug.get('sovled_date')),
                    # 延期天数
                    "delay_days": each_bug.get('delay_days'),
                    # 解决状态
                    "status": Bug_status_constant_responding_English.get(each_bug.get('status'))
                } for each_bug in Bug_condition_search_result if each_bug]
            }
        }
        # 返回数据结构的构造
        return HttpResponse(serialize_json_dumps(json_returns), content_type="application/json")
    else:
        return HttpResponseBadRequest(content=b'request is a bad request')










